import request from './request'

/**
 * 登录请求参数
 */
export interface LoginCredentials {
  username: string;
  password: string;
  rememberMe?: boolean;
}

/**
 * 用户信息接口
 */
export interface Role {
  id: number;
  name: string;
  description?: string;
}

export interface User {
  id: number;
  username: string;
  email: string;
  roles?: Role[];
  created_at?: string;
  updated_at?: string;
}

/**
 * 登录响应数据
 */
export interface LoginResponse {
  access_token: string;
  user: User;
}

/**
 * 注册请求参数
 */
export interface RegisterCredentials {
  username: string;
  password: string;
  confirm_password: string;
}

/**
 * 忘记密码请求参数
 */
export interface ForgotPasswordCredentials {
  email: string;
}

/**
 * 注册响应数据
 */
export interface RegisterResponse {
  message: string;
  user: User;
}

/**
 * 用户登录
 * @param credentials 用户登录凭据
 * @returns 包含token和用户信息的响应
 */
export async function login(credentials: LoginCredentials): Promise<LoginResponse> {
  try {
    const response = await request.post('/v1/users/login', {
      username: credentials.username,
      password: credentials.password,
    });
    
    // request.ts 拦截器已经提取了 response.data，所以直接返回 response
    return response as unknown as LoginResponse;
  } catch (error: any) {
    console.error('登录请求失败:', error);
    // 丰富错误信息，确保包含详细的错误内容
    if (error.response) {
      // 服务器返回了错误响应
      const errorMessage = error.response.data?.msg || error.response.data?.error || error.response.data?.message || '登录请求失败';
      const detailedError = new Error(`${errorMessage} (${error.response.status})`);
      detailedError.name = 'LoginError';
      // 保留原始错误的响应信息
      (detailedError as any).response = error.response;
      throw detailedError;
    } else if (error.request) {
      // 请求已发出但没有收到响应
      throw new Error('网络错误，服务器无响应');
    } else {
      // 请求配置出错
      throw new Error(`请求错误: ${error.message}`);
    }
  }
}

/**
 * 用户注册
 * @param credentials 用户注册凭据
 * @returns 包含token和用户信息的响应
 */
export async function register(credentials: RegisterCredentials): Promise<RegisterResponse> {
  try {
    const response = await request.post('/v1/users/register', credentials);
    
    // request.ts 拦截器已经提取了 response.data，所以直接返回 response
    return response as unknown as RegisterResponse;
  } catch (error) {
    console.error('注册请求失败:', error);
    throw error;
  }
}

/**
 * 忘记密码
 * @param credentials 忘记密码凭据
 * @returns 包含重置信息的响应
 */
export async function forgotPassword(credentials: ForgotPasswordCredentials): Promise<{message: string}> {
  try {
    const response = await request.post('/v1/users/forgot-password', {
      email: credentials.email,
    });
    
    // request.ts 拦截器已经提取了 response.data，所以直接返回 response
    return response as unknown as {message: string};
  } catch (error) {
    console.error('忘记密码请求失败:', error);
    throw error;
  }
}

/**
 * 获取用户信息
 * @param token 用户的认证token
 * @returns 用户信息
 */
export async function getUserInfo(token: string): Promise<User> {
  try {
    const response = await request.get('/v1/auth/me', {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    
    // request.ts 拦截器已经提取了 response.data，所以直接返回 response
    return response as unknown as User;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    throw error;
  }
}
